package com.zys.sac.core.helper;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * rsa密码加密解密工具类
 *
 * Created by zhongjunkai on 2022/10/25.
 */
public class RSAOperator {

    public static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJdxe9wsEvIiN7FJ7URujjLmNk7yrSQIHh1b7ukc9Gk1VWEMMLrhKHEzqRr4zAvR+6JnGAE8P6FGgbD2PJ7kye1P0HiYd8a1OOsDGcBH6oWQupfkBrdvwerROCvmsNJETYpqO9PCN+5TvFe1bZGRXuD+k0na19O4yhGTiImRhOinAgMBAAECgYAmLUSFD1NDWN7jQXifnKMaL7CXHFQLVkSJMCi8+UCf2QMJ8PHD2ojAaL6Dfx6pCClAGm8RuKdtt4FwI9LKV3CTkA1JoKVV7VqqKHny5HsvV/Jno7MjrJIbk5Jm2RE8N2MYkj9bTGgdK55bmxPlT465BiutjKqU9TBoigfVr/mYKQJBAMtRhWxhq93Yew2Got3DKqwJ5fPNOtunXQMWCY2+32HwpkVUNqJsq4dCaOeIOgp4AclmnAQBDiXP7dpJXAHeprsCQQC+rv2d/mtAfRChE5D5ER8v+I3FOmka8sZeVYqf2dVfDLvlrzuhcBel6l07xCUJK+Epawl5TnbcY4c2hYQfHgUFAkEAj9sUTkUlN4hOOJnEbqgCb0tpmoDhXj0iwGY9SD9/CmsdGfyl03KUQtWoJ/npJzMWAIxLY0Hj4rkmD8bMBL6mtQJAHjxxStRE/XzXXjNUEap9X4XyNQwGDpfgjKTTznUkOGY0hT88HWVA2rZHAmsf1Ex477BhWDLw9hFyJ1sUkDqaYQJAfN3r2x3Kgc3+1MiHb5jyXL7BWwqyo6M18L4shyTfm9T3tlVIuB1+yFJI/De0F7QBOY5O5+LrV+rpsFG0OvygGA==";

    public static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXcXvcLBLyIjexSe1Ebo4y5jZO8q0kCB4dW+7pHPRpNVVhDDC64ShxM6ka+MwL0fuiZxgBPD+hRoGw9jye5MntT9B4mHfGtTjrAxnAR+qFkLqX5Aa3b8Hq0Tgr5rDSRE2KajvTwjfuU7xXtW2RkV7g/pNJ2tfTuMoRk4iJkYTopwIDAQAB";

    private RSA rsa;

    public RSAOperator() {
        rsa = new RSA(PRIVATE_KEY, PUBLIC_KEY);
    }

    public RSAOperator(String privateKey, String publicKey) {
        rsa = new RSA(privateKey, publicKey);
    }

    /**
     * 加密（使用公钥）
     *
     * @param rawString
     * @return
     */
    public String encode(String rawString) {
        return rsa.encryptHex(rawString.getBytes(StandardCharsets.UTF_8), KeyType.PublicKey);
    }

    /**
     * 解密（使用私钥）
     * @param encodedString
     * @return
     */
    public String decode(String encodedString) {
        return rsa.decryptStr(encodedString, KeyType.PrivateKey, Charset.defaultCharset());
    }
}
